package com.zxjbyte.yiyi.framework.common.core.pdf.event;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 多行图片水印
 * @Author zhangxingjia
 * @Date 2023/4/24 10:09
 * @Version: 1.0
 */
public class MultilineImageWatermark extends PdfPageEventHelper {

    // logo图片路径
    private final String imagePath;
    // 图片旋转角度，正数顺时针，负数逆时针, 0不旋转
    private final float rotation;
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            Image image = Image.getInstance(FileUtil.getAbsolutePath(imagePath));
            PdfContentByte canvas = writer.getDirectContent();
            // 设置图形状态的填充透明度
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.3f);
            canvas.setGState(gs);
            Rectangle pageSize = document.getPageSize();
            // 基于文档宽度和高度计算
            float pageWidth = pageSize.getWidth();
            float pageHeight = pageSize.getHeight();
            int h = (int) Math.ceil((pageHeight / image.getHeight()));
            int w = (int) Math.ceil((pageWidth / image.getWidth()));
            for (int j = 0; j < w; j++) {
                for (int k = 0; k < h; k++) {
                    image.setAbsolutePosition(pageWidth / w * j, pageHeight / h * k);
                    image.scalePercent(70.0F);
                    image.setRotation(rotation);
                    canvas.addImage(image);
                }
            }
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public MultilineImageWatermark(String imagePath){
        this(imagePath, 45f);
    }

    public MultilineImageWatermark(String imagePath, float rotation){
        this.imagePath = imagePath;
        this.rotation = rotation;
    }
}
